<template>
	<view class="uploader" @click="choose">
	    <slot></slot>
		<view v-if="!custom" class="upload-box" :class="{disabled:disabled}">
			<view class="iconfont icon-plus-large" v-if="!progress"></view>
			<image v-if="mediaType == 'image' && value" :src="value + '?imageView2/1/w/200/h/200'" class="preview"></image>
			<template v-if="mediaType == 'video' && value">
				<image :src="value" class="preview"></image>
				<view class="iconfont icon-arrow-right"></view>
			</template>
			<view v-if="mediaType == 'video' && progress" class="upload-progress">{{progress}}%</view>
			
			<!-- <video v-else-if="mediaType == 'video' && value"  :controls="false" :src="value" :custom-cache="false" class="preview"></video> -->	
		</view>
	</view>
</template>

<script>
	import Http from '@/api/http/http';

	export default {
		props: {
		  initValue:{
			type:String
		  },
		  ratio: {
			type: Number,
			default: 1.5
		  },
		  edit: {
			type: Boolean,
			default: false
		  },
		  multiple: {
			type: Boolean,
			default: false
		  },
		  temporary: {
			type: Boolean,
			default: false
		  },
		  mediaType: {
			type: String,
			default: 'image'
		  },
		  name: {
			type: String
		  },
		  autoUpload: {
			type: Boolean,
			default: true
		  },
		  handClick: {
			type: Boolean,
			default: true
		  },
		  size: {
			type: Number
		  },
		  max: {
			type: Number
		  },
		  url: {
			type: String
		  },
		  visible: {
			type: Boolean,
			default: true
		  },
		  custom: {
			type: Boolean,
			default: false
		  },
		  useNative: { // 使用原生app选择文件
			type: Boolean,
			default: true
		  },
		  disabled: { // 是否禁用
			type:Boolean,
			default: false	
		  },
		  showCapture: Boolean,
		  uploadState: Boolean,
		  success: Function
		  
		  
		},
		data () {
		  return {
			items: [],
			
			style: {},
			value: null,
			progress:null
		  }
		},
		computed:{
			
			uploadUrl:function(){
				if(this.url){
					return this.url;
				}
				
				return '/common/qiniu'
			},
			
			fileName: function(){
				if(this.name){
					return this.name;
				}
				
				return 'file'
			},
			maxlength: function(){
				if(this.max){
					return this.max
				}
				return this.multiple ? 9 : 1
			}
		},
		mounted () {
			this.value = this.initValue;
		},
		methods: {
		  /**
		   * 格式化文件大小
		   * @param {Object} value
		   */
		  formatSize(value){
			if(value < 1024){
				return value + "B";
			}
			if(value < 1048576){
				return Math.floor(value / 1024) + "KB";
			}
			else if(value < 1073741824){
				return Math.floor(value / 1048576) + "MB";
			}
			else {
				return Math.floor(value / 1073741824) + "GB";
			}
		  },
		  choose () {
			if(this.disabled){
				return ;
			}
			let _this = this;
			var config = {
				count: this.maxlength,
				success:(res) => {
					var tempFiles = res.tempFiles ? res.tempFiles : [res];
					
					if(this.maxlength < tempFiles.length){
						global.toast('选择文件超过' + this.maxlength + '个');
						return ;
					}
					
					if(this.size && this.size > 0){
						for(var i=0; i< tempFiles.length; i++){
							if(tempFiles[i].size > this.size){
								global.toast("文件不能大于" + this.formatSize(this.size))
								return ;
							}
						}
					}
					
					this.$emit('select', tempFiles);
					if(!this.autoUpload){
						return ;
					}
					var promises = []
					var ret = []
					
					
					
					for(var i=0; i< tempFiles.length; i++){
					  let index = i
					  promises.push(new Promise((resolve, reject) => {
						  var reqConfig = {
							  method: 'POST', // uni.uploadFile 只能POST请求
							  url: this.uploadUrl, //仅为示例，非真实的接口地址
							  filePath: tempFiles[index].path || tempFiles[index].tempFilePath,
							  name: this.fileName,
							  success: (res) => {
								
								
							  	var statusCode = res.statusCode;
								if(statusCode == 200 && res.data){
									var data = JSON.parse(res.data);
									if(/^\d+$/.test(data.code)){
										statusCode = data.code;
									}
								}
							  	if (statusCode == 401) {
							  	  global.login();
							  	  return;
							  	}
							  	else if(statusCode == 400){
							  		var data = JSON.parse(res.data);
							  		global.toast(data.message);
							  		reject(res);
							  		return;
							  	}
								else if(statusCode != 200){
									var data = JSON.parse(res.data);
									global.toast(data.message||data.msg|| '上传失败');
									reject(res);
									return;
								}
							  	ret[index] = JSON.parse(res.data)
							  	resolve(ret[index])
							  },
							  fail: (err) => {
							  	
							  	reject(err)
							  }
						  }
						  
						  Http.combineHeaders(reqConfig);
						  if (reqConfig.url.indexOf('http') !== 0) {
						    reqConfig.url = global.API_BASE_PATH + reqConfig.url;
						  }
						  var uploadTask = uni.uploadFile(reqConfig);
						  
						  uploadTask.onProgressUpdate((res) => {
							  this.progress = res.progress;
							  if(res.progress == 100){
								//global.hideLoading();
							  }
						  });
						
					  }))
					}
					global.showLoading("上传中……");
					Promise.all(promises).then((ret) => {
						
						global.hideLoading();
						this.progress = null;
						global.toast('上传成功')
						
						var successData = this.multiple ? ret : ret[0];
						
						if(successData){
							this.$emit('on-success', successData);
						}
						
						if(!this.multiple && ret.length > 0){
							
							this.value = this.mediaType == 'video'? ret[0].cover : ret[0].url
						}
					}).catch((error) => {
						global.hideLoading();
						this.progress = null;
						
					});
				}
			};
			
			if(this.mediaType == 'video'){
				config.maxDuration = 15; // 15s
				config.compressed = false;
				delete config.count;
				
				uni.chooseVideo(config);
			}
			else if(this.mediaType == 'image'){
				uni.chooseImage(config);
			}
			else{
				config.maxDuration = 15; // 15s
				//config.mediaType =  [this.mediaType];
				// #ifdef H5
					uni.chooseImage(config)
				// #endif
				// #ifndef H5
					uni.chooseMedia(config)
				// #endif
				
			}
		  },

		  remove (index, item) {
			this.items.splice(index)
		  },
		  showError (message) {
			uni.showToast({
				title:message
			})
		  }
	
		},
		watch: {
		  uploadState (val) {
			if (val === true) {
			  this.$emit('on-trigger-success')
			}
		  }
		}
	}
</script>

<style scoped>
  .uploader{
    display: inline-block;
    vertical-align: top;
    overflow: hidden;
    position: relative;
  }
  .uploader button{
    display: block;
    height: 100%;
  }
  
  .uploader .upload-box{
	  width: 180rpx;
	  height: 180rpx;
	  border-radius:10rpx;
	  border:2rpx solid rgba(229,234,241,1);
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  position: relative;
	  
  }
  .upload-progress{
	  position: absolute;
	  z-index: 1;
	  top:50%;
	  left:50%;
	  font-size:50rpx;
	  transform: translate(-50%,-50%);
  }
  .uploader .upload-box .preview{
		width: 180rpx;
		height: 180rpx;
		border-radius:10rpx;
		position: absolute;
		z-index: 0;
  }
  .uploader .upload-box .iconfont{
	  font-size: 88rpx;
	  color:#A6B2C4;
  }
  
  .disabled .upload-box .iconfont{
	  color:#d2e1f7;
  }
  
  .uploader .upload-box .icon-arrow-right{
	  position: absolute;
	  z-index:2;
	  border:4rpx solid #F1F1F1;
	  color:#F1F1F1;
	  font-size: 60rpx;
	  width: 60rpx;
	  height:60rpx;
	  border-radius: 50%;
  }
</style>
